package com.exsun.gateway.jt809.kafka;

import com.exsun.gateway.jt809.common.DevInfoService;
import com.exsun.gateway.jt809.config.Jt809Config;
import com.exsun.gateway.jt809.data.PushData;
import com.exsun.gateway.jt809.handler.SendMgrHandler;
import com.google.gson.reflect.TypeToken;
import exsun.jt808.data.config.jt808.Jt808ReceiveMsgTopic;
import exsun.jt808.data.config.jt809.Jt809MsgIdConfig;
import exsun.jt808.data.jt809_data.BasicVehicleInfo;
import exsun.jt808.data.jt809_data.SendBaseEntity;
import exsun.jt808.data.jt809_data.video.main.*;
import exsun.jt808.data.kafka_data.KafkaJT808Data;
import exsun.jt808.data.upload_data.jsatl12.AlarmAttachmentInfo;
import exsun.jt808.data.upload_data.jsatl12.AttachmentFileInfo;
import exsun.jt808.data.util.FtpUtils;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 主动上报报警附件目录消息
 */
@Service
public class JT809KafkaUpWarmMsgFileListReqHandler extends JT809KafkaHandleBase<AlarmAttachmentInfo>{
    private Logger logger = LoggerFactory.getLogger(JT809KafkaUpWarmMsgFileListReqHandler.class);

    @Autowired
    private Jt809Config jt809Config;

    @Autowired
    private SendMgrHandler sendMgrHandler;

    @Autowired
    private DevInfoService devInfoService;

    //订阅媒体数据
    @KafkaListener(topics = Jt808ReceiveMsgTopic.alarmAttachmentInfo, containerFactory = "mediaFileListFactory")
    public void batchMediaMsgConsumerListen(List<ConsumerRecord<?, ?>> records, Acknowledgment ack) {
        try{
            //多媒体数据上传
            Type type = new TypeToken<KafkaJT808Data<AlarmAttachmentInfo>>(){}.getType();
            List<PushData> pushs =  super.done(records, type, (obj)->{
                List<PushData> temp = new ArrayList<>();
                BasicVehicleInfo basicVehicleInfo = devInfoService.getBasicVehicleInfo(obj.dvo);
                SendBaseEntity entity = getAlarmFileList(basicVehicleInfo, obj);
                if(entity == null)return temp;
                byte[] body = sendMgrHandler.jt809Encode.upAlarmMediaList((UpAlarmMediaList) entity,Jt809MsgIdConfig.UP_WARN_MSG_FILELIST_REQ);
                PushData pushData = new PushData(Jt809MsgIdConfig.UP_WARN_MSG, body);
                temp.add(pushData);
                return temp;
            });
            //发送错误，则不提交偏移量

            if(pushs == null)return;
            if(pushs.size() != 0){
                logger.info("上报资源列表上传：{}条", pushs.size());
            }
            ack.acknowledge();
        }catch(Exception e){
            logger.info(e.getMessage());
        }
    }
    /**
     * 主动上传含有报警的资源
     * @param objs
     * @return
     */
    private SendBaseEntity getAlarmFileList(BasicVehicleInfo basicVehicleInfo, AlarmAttachmentInfo objs){
        UpAlarmMediaList entity = new UpAlarmMediaList();
        entity.setBasicVehicleInfo(basicVehicleInfo);
        entity.setInfoId(objs.getAlarmFlag());
        entity.setServer(jt809Config.getJt809FtpServer());
//        entity.setServer("221.235.53.40");
        entity.setPort(jt809Config.getJt809FtpPort());
//        entity.setPort(8021);
        entity.setServerUserName(jt809Config.getJt809FtpUserName());
//        entity.setServerUserName("ftpuser");
        entity.setPassWord(jt809Config.getJt809FtpPassword());
//        entity.setPassWord("ftp147258");
        List<AlarmFileInfo> fileLists = new ArrayList<>();
        for (AttachmentFileInfo attachmentFileInfo: objs.getFiles()) {
            AlarmFileInfo fileInfo = new AlarmFileInfo();
            fileInfo.setFileName(attachmentFileInfo.getFileName());
            String filetypeStr = attachmentFileInfo.getFileName().substring(1,2);
            fileInfo.setFileType(Integer.parseInt(filetypeStr));
            fileInfo.setFileSize(attachmentFileInfo.getFileSize());
            fileInfo.setFileUrl("http://" + jt809Config.getVideoServerIp() + ":" + jt809Config.getVideoHttpServerPort() + "/" + jt809Config.getJt809FtpBasePath() + "/AdasDms/" +new SimpleDateFormat("yyyy-MM-dd").format(new Date())
                    + "/" + objs.dvo + "/" + attachmentFileInfo.getFileName());
//            fileInfo.setFileUrl(jt809Config.getJt809FtpBasePath() + "/" + attachmentFileInfo.getFileName());
            fileLists.add(fileInfo);
        }
        entity.setFileLists(fileLists);
        return entity;
    }
}
